package com.zsjt.app.compoent.utils.email;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;

@Component("emailCode")
public class EmailCode {

    private JavaMailSenderImpl mailSender;

    private static final String SUBJECT="app系统邮箱验证通知";


    @Autowired
    public void setMailSender(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }

    public boolean sendEmailCode(String to,String code){
        //1、创建一个复杂的消息邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        String context=
                "<div style='width:640px; background:#fff; border:solid 1px #efefef; margin:0 auto; padding:0 0 0 0'>" +
                        " <table width='560' border='0' align='center' cellpadding='0' cellspacing='0' style=' margin:0 auto; margin-left:30px; margin-right:30px;'>" +
                        "    <tbody>" +
                        "      <td>" +
                        "      <p style='margin:5px 0; padding:3px 0;color:#666; font-size:14px'>金鹰管理系统邮箱验证通知:</p>" +
                        "      <p style='color:#666; font-size:14px'>您正在进行金鹰管理系统用户邮箱验证，您收到的邮箱验证码为： " +
                        "      <p style='color:red; font-size:28px'>" + code +
                        "<p style='margin:5px 0; padding:3px 0;color:#666; font-size:14px'>如果验证码已经失效，请回到金鹰管理系统重新发送验证码，谢谢您的合作！</p>" +
                        "      <p style='margin:5px 0; padding:3px 0;color:#666; font-size:14px'>如非本人操作，请忽略此邮件，由此给您带来的不便请谅解！</p>" +
                        "      <p style='margin:5px 0; padding:3px 0;color:#666; font-size:14px'>感谢您对金鹰管理系统的支持。</p>" +
                        "      </td>" +
                        "    </tbody>" +
                        " </table>" +
                        "</div>";
        try{
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            helper.setSubject(SUBJECT);
            helper.setText(context,true);
            helper.setTo(to);
            helper.setFrom("1243875403@qq.com");
            mailSender.send(mimeMessage);
            return true;
        }catch (MessagingException e){
            e.printStackTrace();
            return false;
        }
    }

    //创建邮箱验证码
    public String getEmailCode() {
        String string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuffer code = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            Random random = new Random();
            int index = random.nextInt(string.length());
            char ch = string.charAt(index);
            code.append(ch);
        }
        return code.toString();
    }

}
